package com.tiancan.design.user.controller;

import com.tiancan.design.user.bean.Result;
import com.tiancan.design.user.service.TokenService;
import com.tiancan.design.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/** @author tiancan */
@RestController
@RequestMapping("/user")
public class UserController {
  private static final String COOKIE_TOKEN_NAME = "login_token";
  @Autowired private UserService userService;
  @Autowired private TokenService tokenService;

  @PostMapping("/register/{email}/{password}/{code}")
  public Result<String> register(
      @PathVariable("email") String email,
      @PathVariable("password") String password,
      @PathVariable("code") String code,
      HttpServletResponse response) {
    Result<String> register = userService.register(email, password, code);
    if (register.getResult()) {
      Cookie cookie = new Cookie(COOKIE_TOKEN_NAME, register.getData());
      cookie.setMaxAge(60 * 60);
      cookie.setPath("/");
      response.addCookie(cookie);
    }
    return register;
  }

  @GetMapping("/isRegistered/{email}")
  public Result<String> isRegistered(@PathVariable("email") String email) {
    return userService.isRegistered(email);
  }

  @PostMapping("/login/{email}/{password}")
  public Result<String> login(
      @PathVariable("email") String email,
      @PathVariable("password") String password,
      HttpServletResponse response) {
    Result<String> login = userService.login(email, password);
    if (login.getResult()) {
      Cookie cookie = new Cookie(COOKIE_TOKEN_NAME, login.getData());
      cookie.setMaxAge(60 * 60);
      cookie.setPath("/");
      response.addCookie(cookie);
    }
    return login;
  }

  @GetMapping("/info/{token}")
  public Result<String> info(@PathVariable("token") String token) {
    return tokenService.info(token);
  }
}
